<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import {
  ElCard,
  ElButton,
  ElInput,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElTag,
  ElEmpty,
  ElPagination,
  ElMessage,
  ElCollapse,
  ElCollapseItem,
  ElDrawer
} from 'element-plus'
import { Search, Refresh, Filter, Document, User } from '@element-plus/icons-vue'
import request from '@/utils/request'

interface User {
  id: string
  loginId: string
  email: string
  nickname?: string
  name?: string
  role: string
  status: string
  createdAt: string
  wallet?: {
    pointsBalance: string
  }
}

interface UserLog {
  id: string
  type: 'recharge' | 'withdrawal' | 'gift' | 'chat_gift'
  userId: string
  user: {
    id: string
    loginId: string
    nickname?: string
    name?: string
  }
  amount?: number
  points?: string
  status?: string
  method?: string
  referenceNo?: string
  quantity?: number
  gift?: {
    id: string
    name: string
    iconUrl?: string
  }
  channel?: {
    id: string
    name: string
  }
  room?: {
    id: string
    title?: string
  }
  receiver?: {
    id: string
    loginId: string
    nickname?: string
    name?: string
  }
  createdAt: string
  description: string
}

interface LogsResponse {
  logs: UserLog[]
  total: number
  page: number
  limit: number
  user?: User
}

const loading = ref(false)
const logs = ref<UserLog[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const selectedUser = ref<User | null>(null)
const showSearchDrawer = ref(false)

// 搜索条件
const searchForm = ref({
  search: '',
  type: 'all',
  startDate: '',
  endDate: ''
})

// 로그 유형 옵션
const logTypeOptions = [
  { label: '전체', value: 'all' },
  { label: '충전', value: 'recharge' },
  { label: '출금', value: 'withdrawal' },
  { label: '라이브 선물', value: 'gift' },
  { label: '채팅 선물', value: 'chat_gift' }
]

// 사용자 로그 가져오기
const fetchUserLogs = async () => {
  try {
    loading.value = true
    const params: any = {
      page: currentPage.value,
      limit: pageSize.value,
      type: searchForm.value.type
    }

    if (searchForm.value.search.trim()) {
      params.search = searchForm.value.search.trim()
    }

    if (searchForm.value.startDate) {
      params.startDate = searchForm.value.startDate
    }

    if (searchForm.value.endDate) {
      params.endDate = searchForm.value.endDate
    }

    const response = await request.get('/api/admin/user-logs', { params })
    const data: LogsResponse = response.data

    logs.value = data.logs
    total.value = data.total
    selectedUser.value = data.user || null
  } catch (error) {
    console.error('사용자 로그 가져오기 실패:', error)
    ElMessage.error('사용자 로그 가져오기 실패')
  } finally {
    loading.value = false
  }
}

// 사용자 로그 검색
const handleSearch = () => {
  currentPage.value = 1
  fetchUserLogs()
  showSearchDrawer.value = false
}

// 검색 초기화
const handleReset = () => {
  searchForm.value = {
    search: '',
    type: 'all',
    startDate: '',
    endDate: ''
  }
  selectedUser.value = null
  currentPage.value = 1
  fetchUserLogs()
  showSearchDrawer.value = false
}

// 페이지 변경
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchUserLogs()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchUserLogs()
}

// 로그 유형 포맷
const formatLogType = (type: string) => {
  const typeMap: Record<string, { label: string; type: 'primary' | 'success' | 'warning' | 'info' | 'danger' }> = {
    recharge: { label: '충전', type: 'success' },
    withdrawal: { label: '출금', type: 'warning' },
    gift: { label: '라이브 선물', type: 'primary' },
    chat_gift: { label: '채팅 선물', type: 'info' }
  }
  return typeMap[type] || { label: type, type: 'info' as const }
}

// 상태 포맷
const formatStatus = (status: string) => {
  const statusMap: Record<string, { label: string; type: 'primary' | 'success' | 'warning' | 'info' | 'danger' }> = {
    pending: { label: '심사 대기', type: 'warning' },
    approved: { label: '승인됨', type: 'success' },
    rejected: { label: '거부됨', type: 'danger' }
  }
  return statusMap[status] || { label: status, type: 'info' as const }
}

// 사용자 표시명 포맷
const formatUserName = (user: any) => {
  return user.nickname || user.name || user.loginId
}

// 숫자 포맷
const formatNumber = (num: string | number) => {
  const n = typeof num === 'string' ? parseInt(num) : num
  return n.toLocaleString()
}

// 금액 포맷
const formatAmount = (amount: number) => {
  return '¥' + amount.toLocaleString()
}

// 시간 포맷
const formatTime = (time: string) => {
  return new Date(time).toLocaleString('ko-KR', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 是否有搜索条件
const hasSearchConditions = computed(() => {
  return searchForm.value.search.trim() ||
         searchForm.value.type !== 'all' ||
         searchForm.value.startDate ||
         searchForm.value.endDate
})

onMounted(() => {
  fetchUserLogs()
})
</script>

<template>
  <div class="mobile-page">
    <!-- 页面头部 -->
    <div class="mobile-page-header">
      <div class="page-title">
        <el-icon class="title-icon"><Document /></el-icon>
        <span>사용자 로그</span>
      </div>
      <div class="header-actions">
        <el-button
          type="primary"
          size="small"
          @click="showSearchDrawer = true"
          :class="{ 'has-conditions': hasSearchConditions }"
        >
          <el-icon><Filter /></el-icon>
          필터
        </el-button>
        <el-button
          size="small"
          :loading="loading"
          @click="fetchUserLogs"
        >
          <el-icon><Refresh /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- 用户信息卡片 -->
    <div v-if="selectedUser" class="mobile-content">
      <el-card class="user-info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <el-icon><User /></el-icon>
            <span>사용자 정보</span>
          </div>
        </template>
        <div class="user-info-grid">
          <div class="info-item">
            <span class="label">사용자 ID</span>
            <span class="value">{{ selectedUser.loginId }}</span>
          </div>
          <div class="info-item">
            <span class="label">이메일</span>
            <span class="value">{{ selectedUser.email }}</span>
          </div>
          <div class="info-item">
            <span class="label">닉네임</span>
            <span class="value">{{ selectedUser.nickname || selectedUser.name || '-' }}</span>
          </div>
          <div class="info-item">
            <span class="label">포인트 잔액</span>
            <span class="value highlight">{{ formatNumber(selectedUser.wallet?.pointsBalance || '0') }}P</span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 로그 목록 -->
    <div class="mobile-content">
      <el-card v-loading="loading" class="logs-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>활동 로그</span>
            <span class="total-count">총 {{ formatNumber(total) }}개</span>
          </div>
        </template>

        <template v-if="logs.length === 0 && !loading">
          <el-empty description="로그 기록이 없습니다" />
        </template>

        <template v-else>
          <div class="logs-list">
            <div
              v-for="log in logs"
              :key="log.id"
              class="log-item"
            >
              <!-- 日志头部 -->
              <div class="log-header">
                <el-tag :type="formatLogType(log.type).type" size="small">
                  {{ formatLogType(log.type).label }}
                </el-tag>
                <span class="log-time">{{ formatTime(log.createdAt) }}</span>
              </div>

              <!-- 用户信息 -->
              <div class="log-user">
                <div class="user-name">{{ formatUserName(log.user) }}</div>
                <div class="user-id">{{ log.user.loginId }}</div>
              </div>

              <!-- 日志描述 -->
              <div class="log-description">
                {{ log.description }}
              </div>

              <!-- 金额/积分信息 -->
              <div v-if="log.amount || log.points" class="log-amount">
                <div v-if="log.amount" class="amount">{{ formatAmount(log.amount) }}</div>
                <div v-if="log.points" class="points">{{ formatNumber(log.points) }} 포인트</div>
              </div>

              <!-- 状态 -->
              <div v-if="log.status" class="log-status">
                <el-tag :type="formatStatus(log.status).type" size="small">
                  {{ formatStatus(log.status).label }}
                </el-tag>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50]"
              :total="total"
              layout="total, prev, pager, next"
              small
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
            />
          </div>
        </template>
      </el-card>
    </div>

    <!-- 搜索抽屉 -->
    <el-drawer
      v-model="showSearchDrawer"
      title="검색 필터"
      direction="btt"
      size="auto"
      class="search-drawer"
    >
      <div class="search-form">
        <div class="form-item">
          <label class="form-label">사용자 검색</label>
          <el-input
            v-model="searchForm.search"
            placeholder="사용자명/이메일/닉네임"
            clearable
          />
        </div>

        <div class="form-item">
          <label class="form-label">로그 유형</label>
          <el-select v-model="searchForm.type" placeholder="로그 유형 선택" style="width: 100%">
            <el-option
              v-for="option in logTypeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </div>

        <div class="form-item">
          <label class="form-label">시작 날짜</label>
          <el-date-picker
            v-model="searchForm.startDate"
            type="date"
            placeholder="시작 날짜 선택"
            style="width: 100%"
          />
        </div>

        <div class="form-item">
          <label class="form-label">종료 날짜</label>
          <el-date-picker
            v-model="searchForm.endDate"
            type="date"
            placeholder="종료 날짜 선택"
            style="width: 100%"
          />
        </div>

        <div class="form-actions">
          <el-button @click="handleReset">초기화</el-button>
          <el-button type="primary" @click="handleSearch">검색</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<style scoped>
.mobile-page {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.mobile-page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.title-icon {
  margin-right: 8px;
  color: var(--el-color-primary);
}

.header-actions {
  display: flex;
  gap: 8px;
}

.header-actions .el-button.has-conditions {
  background: var(--el-color-primary);
  border-color: var(--el-color-primary);
  color: white;
}

.mobile-content {
  padding: 16px;
}

.mobile-content:last-child {
  flex: 1;
  overflow-y: auto;
}

.user-info-card,
.logs-card {
  border-radius: 12px;
  margin-bottom: 16px;
}

.logs-card:last-child {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.card-header .el-icon {
  margin-right: 8px;
  color: var(--el-color-primary);
}

.total-count {
  font-size: 14px;
  color: var(--el-text-color-regular);
  font-weight: normal;
}

.user-info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-item .label {
  font-size: 12px;
  color: var(--el-text-color-regular);
  font-weight: 500;
}

.info-item .value {
  font-size: 14px;
  color: var(--el-text-color-primary);
  font-weight: 500;
}

.info-item .value.highlight {
  color: var(--el-color-primary);
  font-weight: 600;
}

.logs-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.log-item {
  background: var(--el-fill-color-lighter);
  border-radius: 8px;
  padding: 16px;
  border: 1px solid var(--el-border-color-light);
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.log-time {
  font-size: 12px;
  color: var(--el-text-color-regular);
}

.log-user {
  margin-bottom: 8px;
}

.user-name {
  font-size: 14px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.user-id {
  font-size: 12px;
  color: var(--el-text-color-regular);
  margin-top: 2px;
}

.log-description {
  font-size: 14px;
  color: var(--el-text-color-primary);
  line-height: 1.5;
  margin-bottom: 8px;
}

.log-amount {
  margin-bottom: 8px;
}

.amount {
  color: var(--el-color-success);
  font-weight: 600;
  font-size: 14px;
}

.points {
  color: var(--el-color-primary);
  font-weight: 600;
  font-size: 14px;
  margin-top: 4px;
}

.log-status {
  display: flex;
  justify-content: flex-end;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 搜索抽屉样式 */
.search-drawer :deep(.el-drawer__body) {
  padding: 20px;
}

.search-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-label {
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.form-actions {
  display: flex;
  gap: 12px;
  margin-top: 20px;
}

.form-actions .el-button {
  flex: 1;
}

/* 响应式优化 */
@media (max-width: 480px) {
  .mobile-page-header {
    padding: 12px;
  }

  .page-title {
    font-size: 16px;
  }

  .mobile-content {
    padding: 12px;
  }

  .user-info-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .log-item {
    padding: 12px;
  }

  .log-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .log-time {
    align-self: flex-end;
  }
}
</style>
